const crypto = require('crypto-js');
const base64 = require('js-base64').Base64;
const util = require('../lib/util');
const redis = require('../boot/redis').redisClient;

module.exports = {
    /**
     * @param {object} playload
     * @param {string} sessionKey
     * @return {string} 
     */
    encode: function(playload, sessionKey) {
        let base64Code = base64.encode(JSON.stringify(playload));
        let sign = crypto.SHA256(base64Code + sessionKey).toString();
        return `${base64Code}@${sign}`;
    },

    /**
     * @param {string} accessToken
     */
    decode: async function(accessToken) {
        let arr = accessToken.split('@');
        if (arr.length !== 2) {
            throw new Error('accessToken格式错误');
        }
        if (util.isEmpty(arr[0]) || util.isEmpty(arr[1])) return false;
        let playload = JSON.parse(base64.decode(arr[0]));
        let msg = await redis.hget('session', playload.user.id);
        if (util.isEmpty(msg)) {
            throw new Error('sessionKey不存在');        
        }

        let session = JSON.parse(msg);
        let agent = playload['agent'];
        let sign = crypto.SHA256(arr[0]+session[agent]).toString();
        if (sign !== arr[1]) {
            throw new Error('accessToken签名错误');
        }        
        return playload;
    },
};